package com.mj.haier.rrskx.sharding;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.alibaba.fastjson.JSON;
import io.shardingsphere.core.api.algorithm.sharding.ListShardingValue;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.shardingsphere.core.api.algorithm.sharding.ShardingValue;
import io.shardingsphere.core.api.algorithm.sharding.hint.HintShardingAlgorithm;

public class HintTradeShardingAlgorithm implements HintShardingAlgorithm{


    private final Logger log = LoggerFactory.getLogger(HintTradeShardingAlgorithm.class);

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ShardingValue shardingValue) {
        log.debug("shardingValue : {}", JSON.toJSONString(shardingValue));
        log.debug("availableTargetNames : {}", JSON.toJSONString(availableTargetNames));
        List<String> shardingResult = new ArrayList<>();
        availableTargetNames.forEach(targetName -> {
            String suffix = targetName.substring(targetName.lastIndexOf("_"));
            if(StringUtils.isNotBlank(suffix)){
                ListShardingValue<String> shardingValues = (ListShardingValue<String>) shardingValue;
                shardingValues.getValues().forEach(value -> {
                    if (value.equals(suffix)){
                        shardingResult.add(targetName);
                    }
                });
            }
        });
        return shardingResult;
    }
}
